﻿using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using SystemCustomers.DBUtils;
using SystemCustomers.MessageUtils;

namespace SystemCustomers.ManageProjectToCustomers
{
    public partial class AddProjectCustomers : Form
    {
        public AddProjectCustomers()
        {
            InitializeComponent();
            this.IsForSpecificCompany = false;
            InitcombListCompany();
            InitcombListProject();
        }
        #region Properties
        public AddProjectCustomers(string companyName, string projectName, string companyId,
            string idProject, string priceType, string discriptions, string paid, string destination, DateTime startDateProject, DateTime finishDateProject)
        {
            InitializeComponent();
            this.btnAdd.Visible = false;
            this.btnupdate.Visible = true;
            this.IsForSpecificCompany = true;
            this._companyName = companyName;
            this._projectName = projectName;
            this.CompanyId = companyId;
            this.IdProject = idProject;
            this.PriceType = priceType;
            this.Discriptions = discriptions;
            this.Paid = paid;
            PaidorNotPaid(this.Paid);
            this.Destination = destination;
            this.StartDateProject = startDateProject;
            this.FinishDateProject = finishDateProject;
            InitcombListCompany();
            InitcombListProject();
            CheckFileExists();
        }

        private void PaidorNotPaid(string paid)
        {
            if (paid != "שולם")
            {
                radiobPaid.Checked = true;
                radiobNotPaid.Checked = false;
            }
            else
            {
                radiobNotPaid.Checked = true;
                radiobPaid.Checked = false;
            }
        }

        private bool _canAdd = false;

        public bool IsForSpecificCompany { get; set;}

        private string _companyName = string.Empty;

        public new string CompanyName
        {
            get { return _companyName = combListCompany.SelectedItem.ToString(); }
            set { _companyName = value; }
        }

        private string _projectName = string.Empty;

        public string ProjectName
        {
            get { return _projectName = combListProject.SelectedItem.ToString(); }
            set { _projectName = value; }
        }

        public string CompanyId { get; set;}
        
        public string IdProject { get; set;}

        public string PriceType
        {
            get { return txtbPriceType.Text; }
            set { txtbPriceType.Text = value; }
        }

        public string Discriptions
        {
            get { return txtDiscriptions.Text; }
            set { txtDiscriptions.Text = value; }
        }

        public string Paid { get; set;}

        private string _destination = string.Empty;

        public string Destination
        {
            get {return _destination ;}
            set {_destination = value ;}
        }

        public string OldDestination { get; set;}

        public DateTime StartDateProject
        {
            get { return dateStartProject.Value; }
            set { dateStartProject.Value = value; }
        }

        public DateTime FinishDateProject
        {
            get { return dateFinishProject.Value; }
            set { dateFinishProject.Value = value; }
        }

        #endregion Properties

        #region Method
        private void EnableAdd()
        {
            btnAdd.Enabled = btnupdate.Enabled = IsValid() && _canAdd;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private bool IsValid()
        {
            return (txtbPriceType.Text.Trim() != string.Empty);
        }

        public void InitcombListCompany()
        {
            if (IsForSpecificCompany)
            {
                combListCompany.Items.Clear();
                IDToName comp = new IDToName(this._companyName, this.CompanyId);
                combListCompany.Items.Add(comp);
            }
            else
            {
                string idComp = string.Empty;
                string Compname = string.Empty; 
                foreach (DataRow rd in SingletonManagerDb.Instance.DbViewingNameCustandIdCust().Rows)
                {
                    Compname = rd["companyName"].ToString();
                    idComp = rd["idCompany"].ToString();
                    IDToName company = new IDToName(Compname, idComp);
                    combListCompany.Items.Add(company);
                }
            }
            if (combListCompany.Items.Count > 0) combListCompany.SelectedIndex = 0;
        }

        public void InitcombListProject()
        {
            if (IsForSpecificCompany)
            {
                combListProject.Items.Clear();
                IDToName project = new IDToName(this._projectName, this.IdProject);
                combListProject.Items.Add(project);
            }
            else
            {
                foreach (DataRow rd in SingletonManagerDb.Instance.DbViewingProject().Rows)
                {
                    string serviceName = rd["projectName"].ToString();
                    string idService = rd["idProject"].ToString();
                    IDToName service = new IDToName(serviceName, idService);
                    combListProject.Items.Add(service);
                }
            }

            if (combListProject.Items.Count > 0) combListProject.SelectedIndex = 0;
        }

        private void combListCompany_SelectedIndexChanged(object sender, EventArgs e)
        {
            IDToName company = (IDToName)this.combListCompany.SelectedItem;
            if (company == null) return;
            this.CompanyId = company.ID;
            this.CompanyName = company.Name;
        }

        private void combListProject_SelectedIndexChanged(object sender, EventArgs e)
        {
            IDToName project = (IDToName)this.combListProject.SelectedItem;
            if (project == null) return;
            this.IdProject = project.ID;
            this.ProjectName = project.Name;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            bool isAddToDataBase = (from DataRow rd in SingletonManagerDb.Instance.DbViewingProjectToCompany().Rows
                                    let companyId = rd["idCompany"].ToString()
                                    let projectId = rd["idProject"].ToString()
                                    where CompanyId == companyId && IdProject == projectId
                                    select companyId).Any();
            if (!isAddToDataBase)
            {
                if (!radiobPaid.Checked)
                    Paid = "שולם";
                else
                    Paid = "לא שולם";
                if (!SingletonManagerDb.Instance.DbInsertManageProjectToCompany(IdProject, CompanyId, PriceType, CompanyName, ProjectName, Discriptions, Paid, StartDateProject, FinishDateProject, Destination)) return;
                LogUtils.WriteToLog(String.Format(" Manage Company To Project: {0} And {1}", CompanyName, ProjectName));
                LogUtils.SystemEventLogsInformation(String.Format(" Manage Company To Project: {0} And {1}", CompanyName, ProjectName));
                new MessageBoxText("נוסף בהצלחה").OkMessaageBox();
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                LogUtils.WriteToLog(String.Format(" Error Company To Project the company and project exist: {0} And {1}", CompanyName, ProjectName));
                LogUtils.SystemEventLogsInformation(String.Format(" Error Company To Project the company and project exist: {0} And {1}", CompanyName, ProjectName));
                new MessageBoxText("קיים במערכת אותו פרויקט לספק הנבחר").OkMessaageBox();
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            LogUtils.WriteToLog(" Exit From Manage Company To Project");
            LogUtils.SystemEventLogsInformation(" Exit From Manage Company To Project");
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btnupdate_Click(object sender, EventArgs e)
        {
                if (this.OldDestination != this.Destination && this.OldDestination != string.Empty && File.Exists(this.OldDestination))
                    File.Delete(this.OldDestination);
            if (!radiobPaid.Checked)
                Paid = "שולם";
            else
                Paid = "לא שולם";
            if (!SingletonManagerDb.Instance.DbUpdateProjectToCompany(this.Destination, Discriptions, Paid, PriceType, CompanyId, IdProject, this.StartDateProject, this.FinishDateProject)) return;
            LogUtils.WriteToLog(" Update Manage Company To Project");
            LogUtils.SystemEventLogsInformation(" Update Manage Company To Project");
            new MessageBoxText("עודכן בהצלחה").OkMessaageBox();
            this.DialogResult = DialogResult.OK;
            this.Close();
           
        }

        private void txtbPriceType_TextChanged(object sender, EventArgs e)
        {
            if (!MyRegEx.Validate(txtbPriceType.Text, MyRegEx.OnlyCharsSpacesAndApostropheDigitsHebrew))
            {
                epManageProjectToCompany.SetError(txtbPriceType, "קלט לא חוקי");
                _canAdd = false;
            }
            else
            {
                epManageProjectToCompany.SetError(txtbPriceType, string.Empty);
                _canAdd = true;
            }
            EnableAdd();
        }

        private void txtbPriceType_MouseHover(object sender, EventArgs e)
        {
            toolTipManageProjectToCompany.SetToolTip(txtbPriceType, "שדה חובה");
        }

        private void CheckFileExists()
        {
            if (File.Exists(this.Destination))
                btnOpenFile.Visible = true;
            else
                btnOpenFile.Visible = false;
        }

        private void buttonOpenPathFile_Click(object sender, EventArgs e)
        {
            this.OldDestination = this.Destination;
            if (!System.IO.Directory.Exists(String.Format(@"{0}\DataFiles\{1}", Application.StartupPath, this.CompanyId)))
            {
                System.IO.Directory.CreateDirectory(String.Format(@"{0}\DataFiles\{1}", Application.StartupPath, this.CompanyId));
            }
            this.openFile.FileName = "Choose File";
            this.openFile.Title = @"Insert an File";
            this.openFile.Filter = @"Microsoft Word (*.doc, *.docx)|*.doc;*.docx|PDF files (*.pdf)|*.pdf|Image files (*.jpg,*.tif,*.tiff)|*.jpg;*.tif;*.tiff";
            if (Directory.Exists(this.Destination))
                this.openFile.InitialDirectory = this.Destination;
            if (this.openFile.ShowDialog() == DialogResult.OK)
            {
                if (this.openFile.CheckFileExists)
                {
                    this.Destination = String.Format(@"{0}\DataFiles\{1}\{2}", Application.StartupPath, this.CompanyId, openFile.SafeFileName);
                    System.IO.File.Copy(openFile.FileName, this.Destination, true);
                    btnOpenFile.Visible = true;
                }
            }
            openFile.Dispose();
        }

        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            if (this.Destination != string.Empty)
                System.Diagnostics.Process.Start(this.Destination);
        }

        private void btnOpenFile_MouseHover(object sender, EventArgs e)
        {
            toolTipManageProjectToCompany.SetToolTip(btnOpenFile, "Open File: " + this.Destination);
        }
        #endregion Method
    }
}
